package com.example.finaltool.service;

import com.example.finaltool.annotations.Timer;
import com.example.finaltool.consts.Table;
import com.example.finaltool.consts.task.CmmExtTask;
import com.example.finaltool.consts.task.Task;
import com.example.finaltool.mapper.CmmFunctionExtConfigMapper;
import com.example.finaltool.model.DepInfo;
import com.example.finaltool.model.config.Data;
import com.example.finaltool.utils.PrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CmmFunctionExtConfigService {

    CmmFunctionExtConfigMapper mapper;

    @Autowired
    public CmmFunctionExtConfigService(CmmFunctionExtConfigMapper mapper) {
        this.mapper = mapper;
    }

    @Timer(Table.CMM_EXT_CONFIG)
    @Transactional(rollbackFor = Exception.class)
    public void save(Data data, Map<String, String> core, DepInfo info) {
        String corpId = data.getCorpId();
        info.subIds().forEach(subId -> {
            List<Long> ids = getExistIds(corpId, subId);
            for (CmmExtTask t : Task.extTask(corpId, core)) {
                if (ids.contains(t.getId())) {
                    PrintUtils.showExist(Table.CMM_EXT_CONFIG, t.getName());
                }
                else {
                    if (Task.extNeed.contains(t.getId()) && StringUtils.isBlank(core.get(Task.getExtLabel(t.getName())))) {
                        continue;
                    }
                    mapper.save(t.getId(), t.getName(), t.getType(), t.getUrl(), t.getCorpId(), t.getPlatform(), subId);
                }
            }
        });
    }

    private List<Long> getExistIds(String corpId, Long subId) {
        return mapper.queryExistIds(corpId, subId);
    }
}
